package demo.java.lang.management.jvm;

import demo.java.lang.management.vo.JVMProcessStat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;


/**
 * 收集进程内的信息，如各个状态线程个数，负载等
 * 
 * @date 16/1/18
 */
public class ProcessStatCollector {

    private static final Logger logger = LoggerFactory.getLogger(ProcessStatCollector.class);

    private ThreadingCollector threadingCollector;

    private OperatingSystemMXBean OS;

    private CpuRateCollector cpuRateCollector;

    private RuntimeMXBean Runtime;

    public ProcessStatCollector(ThreadingCollector threadingCollector, CpuRateCollector cpuRateCollector,
            OperatingSystemMXBean OS, RuntimeMXBean Runtime) {
        this.threadingCollector = threadingCollector;
        this.cpuRateCollector = cpuRateCollector;
        this.OS = OS;
        this.Runtime = Runtime;
    }

    public JVMProcessStat collect() {
        JVMProcessStat processStat = new JVMProcessStat();
        try {
            processStat.setDaemonThreadCount(threadingCollector.getDaemonThreadCount());
            processStat.setPeakThreadCount(threadingCollector.getPeakThreadCount());
            processStat.setSystemLoadAverage(JVMUtils.formatDouble(OS.getSystemLoadAverage()));
            processStat.setThreadCount(threadingCollector.getThreadCount());
            processStat.setTotalStartedThreadCount(threadingCollector.getTotalStartedThreadCount());
            processStat.setWaitingThreadCount(threadingCollector.getWaitingThreadCount());
            processStat.setTimedWaitingThreadCount(threadingCollector.getTimedWaitingThreadCount());
            processStat.setBlockedThreadCount(threadingCollector.getBlockedThreadCount());
            processStat.setRunnableThreadCount(threadingCollector.getRunnableThreadCount());

            processStat.setCpuRate(cpuRateCollector.collect());

            processStat.setUptime(Runtime.getUptime());

            threadingCollector.resetPeakThreadCount();
        } catch (Throwable e) {
            logger.error("ProcessStatCollector collect error, {}", e.getMessage());
            return null;
        }

        return processStat;
    }
}
